from apps.meiduo_admin.serializers.image import ImageSerializer, SKUSeriazlier
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SKUImage
from apps.meiduo_admin.utils import PageNum
from rest_framework.views import APIView
from apps.goods.models import SKU
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client


class ImageView(ModelViewSet):
    serializer_class = ImageSerializer
    queryset = SKUImage.objects.all()
    pagination_class = PageNum

    # 视图集的新增是用create方法
    # 这里重写create方法
    # 重写拓展类的保存业务逻辑
    def create(self, request, *args, **kwargs):
        # 获取参数
        # 获取sku_id
        sku_id = request.data.get('sku')
        # 校验参数
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return Response({'mgs': '商品不存在'})
        # 创建FastDFS连接对象
        client = Fdfs_client('meiduo_mall/utils/fastdfs/client.conf')
        # 获取前端传递的image文件
        data = request.FILES.get('image')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(data.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']

        # 保存图片
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 返回结果
        return Response({
            'id': img.id,
            'sku': sku_id,
            'image': img.image.url
        }, status=201)  # 前端需要接受201状态

    def update(self, request, *args, **kwargs):
        """更新图片数据"""
        sku_id = request.data.get('sku')
        old_sku_image = self.get_object()  # 通过pk获取需要更新的图片对象，看源码
        # 校验参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return Response({'mgs': '商品不存在'})

        client = Fdfs_client('meiduo_mall/utils/fastdfs/client.conf')
        image_data = request.FILES.get('image')
        result = client.upload_appender_by_buffer(image_data.read())
        if result['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = result['Remote file_id']
        # 更新sku 和图片信息 并保存
        old_sku_image.image = image_url
        old_sku_image.sku = sku
        old_sku_image.save()

        return Response({
            'id': old_sku_image.id,
            'sku': sku_id,
            'image': old_sku_image.image.url
        }, status=201)


class SKUView(APIView):

    def get(self, request):
        data = SKU.objects.all()
        ser = SKUSeriazlier(data, many=True)
        return Response(ser.data)
